package com.atgouwu.mall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atgouwu.mall.common.utils.HttpUtils;
import com.atgouwu.mall.common.utils.R;
import com.atgouwu.mall.common.vo.MemberResponseVo;
import com.atgouwu.mall.auth.feign.MemberFeignService;
import com.atgouwu.mall.auth.vo.SocialUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

import static com.atgouwu.mall.common.constant.AuthServerConstant.LOGIN_USER;

/**
 * 社交登录
 */
@Slf4j
@Controller
public class OAuth2Controller {

    @Autowired
    private MemberFeignService memberFeignService;

    //微博登录(授权回调页)
    @GetMapping(value = "/oauth2.0/weibo/success")
    public R weibo(@RequestParam("code") String code, HttpSession session) throws Exception {
        Map<String, String> map = new HashMap<>();
        map.put("client_id", "793359824"); //基本信息AppKey
        map.put("client_secret", "d48c52192dab3ad4299cddd8ebd1190f"); //基本信息AppSecret
        map.put("grant_type", "authorization_code");
        map.put("redirect_uri", "http://hotlmall.com/authServer/oauth2/weibo/success"); //授权回调页
        map.put("code", code);
        HttpResponse response = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "post", new HashMap<>(), map, new HashMap<>()); //根据回调的code获取access_token
        if (response.getStatusLine().getStatusCode() == 200) {
            String json = EntityUtils.toString(response.getEntity());
            SocialUser socialUser = JSON.parseObject(json, SocialUser.class); //社交用户
            //log.info("accessToken：{}", socialUser.getAccess_token()); //当前用户如果是第一次进网站，自动注册进来（为当前社交用户生成一个会员信息，以后这个社交账号就对应指定的会员）
            R oauthLogin = memberFeignService.oauthLogin(socialUser); //登录或注册这个社交用户(远程调用member服务)
            if (oauthLogin.getCode() == 200) {
                MemberResponseVo data = oauthLogin.getData("data", new TypeReference<MemberResponseVo>() {
                });
                log.info("登录成功：用户信息：{}", data.toString()); //登录后用户信息存入session,再将k为JSESSIONID和值为sessionId存入cookie返给浏览器,浏览器访问会带cookie,根据JSESSIONID获取session
                session.setAttribute(LOGIN_USER, data); //跨域(session共享问题):设置cookie父域名:cookie.setDomain(".baidu.com"); 集群(session不同步问题):SpringSession+Redis+Cookie父域名
                return R.ok(); //登录成功跳回首页
            } else {
                return R.error();
            }
        } else {
            return R.error();
        }
    }

}
